package h0904;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 两数相加
 * @date 2024/9/4 22:29
 */
public class TwoNumAdd {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode();
        ListNode head = dummy;
        int carry = 0;
        while (l1 != null && l2 != null) {
            int value = (l1.val + l2.val + carry) % 10;
            head.next = new ListNode(value);
            carry = (l1.val + l2.val + carry) / 10;
            l1 = l1.next;
            l2 = l2.next;
            head = head.next;
        }
        while (l1 != null) {
            int value = (l1.val + carry) % 10;
            head.next = new ListNode(value);
            carry = (l1.val + carry) / 10;
            l1 = l1.next;
            head = head.next;
        }
        while (l2 != null) {
            int value = (l2.val + carry) % 10;
            head.next = new ListNode(value);
            carry = (l2.val + carry) / 10;
            l2 = l2.next;
            head = head.next;
        }
        if (carry != 0) {
            head.next = new ListNode(carry);
            head = head.next;
        }
        return dummy.next;
    }
}
